
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BasicMessageChannelDemo extends StatefulWidget {
  @override
  _BasicMessageChannelDemoState createState() => _BasicMessageChannelDemoState();
}

class _BasicMessageChannelDemoState extends State<BasicMessageChannelDemo> {
  // 创建 BasicMessageChannel 实例
  static const BasicMessageChannel<String> _basicMessageChannel =
      BasicMessageChannel<String>('samples.flutter.io/basic_message', StringCodec());

  String _messageFromNative = '暂无消息';
  final TextEditingController _textController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 监听来自原生的消息
    _basicMessageChannel.setMessageHandler(_handleMessageFromNative);
  }

  // 处理来自原生的消息
  Future<String> _handleMessageFromNative(String? message) async {
    setState(() {
      _messageFromNative = message ?? '收到空消息';
    });
    // 返回回复给原生
    return 'Flutter已收到消息: $message';
  }

  // 发送消息给原生
  void _sendMessageToNative() async {
    try {
      final String? reply = await _basicMessageChannel.send(_textController.text);
      setState(() {
        _messageFromNative = '原生回复: $reply';
      });
    } on PlatformException catch (e) {
      setState(() {
        _messageFromNative = '错误: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BasicMessageChannel 示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _textController,
              decoration: InputDecoration(
                labelText: '输入要发送的消息',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _sendMessageToNative,
              child: Text('发送消息到原生'),
            ),
            SizedBox(height: 20),
            Text(
              '来自原生的消息:',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(_messageFromNative),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _textController.dispose();
    // 移除消息处理器
    _basicMessageChannel.setMessageHandler(null);
    super.dispose();
  }
}
